from rest_framework import status
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage
from apps.meiduo_admin.serializers.image import SKUImageSerializer
from apps.meiduo_admin.utils import PageNum

from rest_framework.views import APIView
from rest_framework.response import Response
from apps.goods.models import SKU
from apps.meiduo_admin.serializers.image import SKUSeriazlier


class SKUImageView(ModelViewSet):

    queryset = SKUImage.objects.all()

    serializer_class = SKUImageSerializer

    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        # - 1 接收参数 校验
        sku_id = request.data.get('sku')
        image = request.FILES.get('image')
        # 把图片上传到 fastdfs里
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 上传
        result = client.upload_by_buffer(image.read())

        if result.get("Status") != 'Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 取出在fastdfs里的地址  把这个地址 保存到数据库
        file_id = result.get("Remote file_id")
        print("file_id", file_id)

        # - 3 把图片的地址和sku_id一切用模型类SKUImage保存到数据库
        SKUImage.objects.create(sku_id=sku_id, image=file_id)

        # - 4 返回响应
        return Response(status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        # 接收参数  效验
        sku_id = request.data.get('sku')
        image = request.FILES.get('image')
        pk = kwargs.get('pk')
        print('kwargs', kwargs)

        # 把图片上传到 fastdfs里
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image.read())

        if result.get('Status') != 'Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)

        file_id = result.get('Remote file_id')
        print('file_id', file_id)

        sku_image = SKUImage.objects.get(id=pk)
        sku_image.image = file_id
        sku_image.save()

        return Response(status=status.HTTP_201_CREATED)

    # def destroy(self, request, *args, **kwargs):
        # 获取要删除对象的 id
        # 查询要删除的对象
        # 对象.image
        #
        # 从fastdfs里删除
        # from fdfs_client.client import Fdfs_client
        # 创建FastDFS 连接对象
        # client = Fdfs_client('utils/fastdfs/client.conf')
        # client.delete_file()
        # 对象.delete()
        # pass


class SKUView(APIView):

    def get(self,request):
        data = SKU.objects.all()
        ser = SKUSeriazlier(data, many=True)
        return Response(ser.data)


